package leesoft.gocrm.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.collections.ExtendedProperties;

public class PropertyManager {

	private static PropertyManager instance;
	private final static String PROP_FILE_NAME="/gocrm.properties";
	private final static String MAP_KEY="com.gocrm.mapapi.key";
	private final static String POSITION_SRC_KEY="http://localhost:8888/positions.example.xml";
	private final static String GCONTACT_USER_NAME_KEY="com.gocrm.contact.username";
	private final static String GCONTACT_PASSWORD_KEY="com.gocrm.contact.password";
	private final static String GCONTACT_GROUP_NUM_KEY="com.gocrm.contact.groups.totalnum";
	private final static String GCONTACT_GROUP_PREFIX="com.gocrm.contact.groups.";
	private ExtendedProperties extProperties=null;
	
	private PropertyManager(){
		ExtendedProperties defaultProperties = loadDefaultProperties(PROP_FILE_NAME);
		if(defaultProperties!=null)
			extProperties=defaultProperties;
	}
	private ExtendedProperties loadDefaultProperties(String filename)
	{
		 InputStream inputStream = null;
	     ExtendedProperties defaultProperties = new ExtendedProperties();

	     try
	     {
	    	 inputStream = getClass()
	                    .getResourceAsStream(filename);
	         if (inputStream != null)
	         {
	        	 defaultProperties.load(inputStream);
	         }
	        }
	        catch (IOException ioe)
	        {
	        	Logger.global.log(Level.SEVERE, "Can't load the app configuration");
	        }
	        finally
	        {
	            try
	            {
	                if (inputStream != null)
	                {
	                    inputStream.close();
	                }
	            }
	            catch (IOException ioe)
	            {
	            	Logger.global.log(Level.SEVERE, "Can't close the app configuration");
	            }
	        }
	        return defaultProperties;
	}
	
	public static synchronized PropertyManager getInstance()
	{
		if(instance==null)
		{
			instance=new PropertyManager();
		}
		return instance;
	}
	public String getMapAPIKey()
	{
		return extProperties.getString(MAP_KEY);
	}
	public String getGContactApiUserName()
	{
		return extProperties.getString(this.GCONTACT_USER_NAME_KEY);
	}
	public String getGContactApiPassword()
	{
		return extProperties.getString(this.GCONTACT_PASSWORD_KEY);
	}
	public List<String> getGDataContactsGroups()
	{
		ArrayList<String> result=new ArrayList<String>();
		int totalGroupsNumber=extProperties.getInt(this.GCONTACT_GROUP_NUM_KEY);
		for(int i=0;i<totalGroupsNumber;i++)
		{
			result.add(extProperties.getString(this.GCONTACT_GROUP_PREFIX+i));
		}
		return result;
	}
}
